package com.xiaobai.frame.config.jwt;


import com.xiaobai.common.utils.tool.Func;
import com.xiaobai.frame.utils.RedisTool;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

import static com.xiaobai.common.utils.TokenUtil.getTokenId;
import static com.xiaobai.frame.utils.RedisKey.REFRESH_TOKEN;


@Component
public class TokenHandler implements HandlerInterceptor {
    @Resource
    RedisTool redisTool;
    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        try {
            String token = request.getHeader("token");
            if (Objects.isNull(token)) {
                return false;
            }
            String id = getTokenId(token);
            if (Objects.isNull(id)) {
                return false;
            }
            Object cacheObject = redisTool.getCacheObject(REFRESH_TOKEN+id);
            if (Func.isNull(cacheObject)) {
                return true;
            }
//            如果拿刷新token过来不予通过
            return !Func.equals(cacheObject, token);
        } catch (Exception e) {
            return false;
        }
    }
}
